let http = require('http');
let fs = require("fs");
let nunjucks = require('nunjucks');
const Son = require('./home/controller/Son');

let serve = http.createServer(async function (req, res) {
    let postDate = '';
    let url = req.url;
    console.log(url);
    let session = [];

    req.cookies = {};
    let cookie = req.headers.cookie;
    if(cookie){
        let cookiesArr = {}
        cookie.split('; ').forEach(element => {
            console.log(element);
            let cookieKeyAndVal  = element.split('=');
            cookiesArr[cookieKeyAndVal[0]] = cookieKeyAndVal[1]
        });
        req.cookies = cookiesArr;
        console.log(cookiesArr);
    }
    let node_session = null;
    if(!req.cookies.node_session){
        let node_session = new Date().getTime() + Math.random();
        res.setHeader('Set-Cookie','node_session =' + node_session);
    }else{
        node_session = req.cookies.node_session;
        if(session[node_session]){
            req.session = session[node_session];
        }
    }
    //请求时发送的数据
    req.on('data', function (chunk) {
        postDate += chunk;
    })

    req.on('end', async function () {
        res.setHeader("Contenet-type", "text/html:charset=utf8");
        console.log(postDate);
        let result = ''
        let action = '';
        let son = new Son(req, res, nunjucks);
        if (url === '/') {
            result = nunjucks.render('all.html', '')
        } else if (url.indexOf('register.html') > -1) {
            result = nunjucks.render('register.html', '')
        } else if (url.indexOf('login.html') > -1) {
            result = nunjucks.render('login.html')
            // console.log(result);
        } else if (req.method == 'POST' && postDate) {
            let query = url.split('?')[1];
            let queryArry = query.split('&');
            let newArr = [];
            for (let k in queryArry) {
                let temArr = queryArry[k].split('=');
                newArr[temArr[0]] = temArr[1];
            }
            action = newArr['action']
            console.log(newArr);
            let postarry = postDate.split('&')
            let newarr = [];
            for (let val in postarry) {
                console.log(postarry[val]);
                let arrsplit = postarry[val].split('=');
                newarr[arrsplit[0]] = arrsplit[1];
            }
            req.post = newarr;
            console.log(action);

            result = await son[action]();
        }
        if(res.session){
            console.log('-------'+ res.session);
            session[node_session]=JSON.stringify(res.session);
        }
        res.write(result)
        res.end()
    })
})
serve.listen(3000, function () {
    console.log("服务已启动: http://127.0.0.1:3000");
})